import { _decorator, Component, Node, SkeletalAnimation } from 'cc';
import { GlobalEnum } from '../../../Init/Config/GlobalEnum';
import { GlobalTmpData } from '../../../Init/Config/GlobalTmpData';
import { clog } from '../../../Init/Tools/ColorLog';
const { ccclass, property } = _decorator;

@ccclass('PeopleAnim')
export class PeopleAnim extends Component {
    protected _curClip: GlobalEnum.PeopleClips = null;
    @property(SkeletalAnimation)
    protected anim: SkeletalAnimation = null;
    /**当前动画播放时对应的时间缩放系数 */
    private _curAnimtimeScale = 1.0;
    /**记录所有clip的初始速度 */
    private _clipInitSpd: { [name: string]: number } = null;

    //当前动画额外的速度
    private _extralAnimSpd = 1.0;

    protected onEnable() {
        this.resetAnim();
    }

    protected onDisable() {
        this.anim.stop();
    }

    protected resetAnim() {
        this.anim.useBakedAnimation = true;
        this._curClip = null;
        this._curAnimtimeScale = 1.0;
        this._extralAnimSpd = 1;
        this.playAnim(GlobalEnum.PeopleClips.Idle);
    }

    //记录所有clip的初始速度
    protected setInitClipSpd() {
        if (this._clipInitSpd) return;
        this._clipInitSpd = {};
        for (const key in this.anim.clips) {
            const clip = this.anim.clips[key];
            const state = this.anim.getState(clip.name);
            this._clipInitSpd[clip.name] = state.speed || 1;
        }
    }

    /**播放动画 */
    public playAnim(clipName: GlobalEnum.PeopleClips, isForth = false, spdRate = 1.0) {
        if (!isForth && clipName == this._curClip) return;
        this.setInitClipSpd();

        if (!this._clipInitSpd[clipName]) {
            clog.warn('没有' + clipName);
            return;
        };

        this._curClip = clipName;
        //设定播放速度
        this._extralAnimSpd = spdRate;
        this._curAnimtimeScale = GlobalTmpData.timeScale * spdRate;
        let state = this.anim.getState(clipName);
        state.speed = this._clipInitSpd[clipName] * this._curAnimtimeScale;


        //动作融合 
        this.anim.crossFade(clipName, 0.2);
    }

    public customUpdate(dt) {
        this.checkTimeScale();
    }

    /**检测时间缩放系数 */
    private checkTimeScale() {
        const curSpd = GlobalTmpData.timeScale * this._extralAnimSpd;
        if (this._curAnimtimeScale != curSpd) {
            //动画变速
            this._curAnimtimeScale = curSpd;
            //
            this.setCurAnimScale();
        }
    }
    /**改变当前动画的播放速度 */
    protected setCurAnimScale() {
        if (!this._curClip) return;
        let state = this.anim.getState(this._curClip);
        if (state.isPlaying) {
            state.speed = this._clipInitSpd[this._curClip] * this._curAnimtimeScale;
        }

    }

}

